package com.xunk.scene.handler;

import com.xunk.scene.domain.SceneConditionEquipment;
import com.xunk.scene.handler.equipment.ConditionEquipmentLeaf;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.naming.OperationNotSupportedException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.scene.handler
 * @ClassName: ConditionEquipmentHandle
 * @Author: luanzhiwei
 * @Description:
 * @Date: 2021/5/11 10:40
 * @Version: 1.0
 */
@NoArgsConstructor
@Slf4j
public class ConditionBranch extends DefaultConditionHandler implements IConditionHandler {

    List<IConditionHandler> conditionHandlers = new ArrayList<>();


    /**
     * 判断条件是否满足
     *
     * @param oneMatchFlag true满足一条即可，false 需全部满足
     * @return
     * @throws OperationNotSupportedException
     */
    @Override
    public boolean match(boolean oneMatchFlag) throws OperationNotSupportedException {
        if (CollectionUtils.isEmpty(conditionHandlers)) {
            //如果不包含子节点，默认是不匹配
            log.info("存在空枝节点，默认返回false");
            return false;
        }
        Iterator<IConditionHandler> iterator = conditionHandlers.iterator();
        while (iterator.hasNext()) {
            log.info("分支节点包含子节点，调用子节点handle");
            IConditionHandler next = iterator.next();
            boolean match = next.match(oneMatchFlag);
            if (oneMatchFlag) {
                //如果匹配一条即可
                if (match) {
                    //存在一条实际匹配，直接返回true
                    return match;
                }
            } else {
                //如果必须全部匹配
                if (!match) {
                    //有一条不匹配，直接返回false
                    return match;
                }
            }
        }
        if (oneMatchFlag) {
            //匹配一条即可，但没有一条匹配
            return false;
        } else {
            //需全部匹配，但没有一条不匹配
            return true;
        }
    }

    /**
     * 添加子元素
     *
     * @param component
     */
    @Override
    public void add(IConditionHandler component) throws OperationNotSupportedException {
        this.conditionHandlers.add(component);
    }

    /**
     * 添加子元素集合
     *
     * @param components
     */
    @Override
    public void addAll(List<IConditionHandler> components) throws OperationNotSupportedException {
        this.conditionHandlers.addAll(components);
    }

    /**
     * 删除子元素
     *
     * @param component
     */
    @Override
    public void remove(IConditionHandler component) throws OperationNotSupportedException {
        this.conditionHandlers.remove(component);
    }

}
